//https://leetcode.cn/problems/binary-tree-postorder-traversal/description/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) 
    {
        TreeNode* cur=root;
        stack<TreeNode*> st;
        vector<int> ret;
        TreeNode* prev=nullptr;

        while(cur || !st.empty())
        {
            while(cur)
            {
                st.push(cur);
                cur=cur->left;
            }    

            TreeNode* top=st.top();
            if(top->right==nullptr || top->right==prev)
            {
                st.pop();
                ret.push_back(top->val);
                prev=top;
            }
            else
            {
                cur=top->right;
            }
        }

        return ret;
    }
};

//https://leetcode.cn/problems/binary-tree-level-order-traversal/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) 
    {
        vector<vector<int>> ret;
        if(root==nullptr)
        return ret;
        queue<TreeNode*> q;
        q.push(root);

        while(!q.empty())
        {
            int sz=q.size();
            vector<int> temp;
            for(int i=0;i<sz;i++)
            {
                TreeNode* t=q.front();
                q.pop();
                temp.push_back(t->val);
                if(t->left)
                q.push(t->left);
                if(t->right)
                q.push(t->right);
            }
            ret.push_back(temp);
        }  

        return ret;
    }
};